package com.kehutong.wwin.event.util;

import com.kehutong.common.DoveClient;
import com.kehutong.wwin.event.entity.Event;
import org.coraframework.json.JSON;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Ioc;

public class EventWorker implements Runnable {
	
	static Logger logger = LoggerFactory.getLogger(EventWorker.class);
	
	private static final JdbcSession jdbcSession;
	private static final DoveClient doveClient;
	
	static {
		doveClient = Ioc.getInstance(DoveClient.class);
		jdbcSession = Ioc.getInstance(JdbcSession.class);
	}
	
	public EventWorker(Event event) {
		this.event = event;
	}
	
	private final Event event;

	@Override
	public void run() {
		try {
			long beginTime = System.nanoTime();
			
			JSONObject rs = doveClient.post("/wwin" + event.getNoticeUrl(), http->{
				http.addHeader("companyNo", event.getKhtid());
				JSONObject jsonObject = JSON.parseObject(event.getContent());
				jsonObject.forEach((k, v)->http.addParam(k, v.toString()));
			});
			
			int code = rs.getIntValue("code");
			if (rs.getIntValue("code") == 200) {
				event.setStatus(EventStatus.SUCCUSS);
			} else {
				event.setStatus(EventStatus.FAIL);
				event.setExceptions(code + ":" + rs.getString("message"));
			}
			jdbcSession.updateById(event);
			long endTime = System.nanoTime();
			logger.info("exe time: evnet:{}, [ {} ] ms", event.getNoticeUrl(), (endTime - beginTime)/1000000);
		} catch (Throwable e) {
			logger.error("", e);
			event.setStatus(EventStatus.FAIL);
			event.setExceptions(e != null ? e.toString() : null);
			jdbcSession.updateById(event);
		}
	}
    

}
